from django import forms
from django.forms.formsets import formset_factory
from inventory.models import Item,Location
import re

FIELD_CHOICES = (
	('CAS', 'CAS #'),
	('NAME', 'Name'),
	('MOLFORM', 'Molecular Formula'),
	('LOC', 'Location'),
	('SUP', 'Supplier'),
)

COMPARATOR_CHOICES = (
	('IS', 'is'),
	('CONTAINS', 'contains'),
	('STARTSWITH', 'starts with'),
	('ENDSWITH', 'ends with'),
)

ACTION_CHOICES = (
	('MOVE', 'Move selected items'),
	('DELETE', 'Delete selected items'),)


class SearchForm(forms.Form):
	field = forms.ChoiceField(choices=FIELD_CHOICES)
	comparator = forms.ChoiceField(choices=COMPARATOR_CHOICES,initial='CONTAINS')
	value = forms.CharField()
	
	def clean_value(self):
		cd = self.cleaned_data
		field = cd['field']
		cd['value'] = cd['value'].strip()
		
		#if field=='CAS' and not re.search(r'^[0-9]{1,6}-[0-9]{2}-[0-9]$', value):
		#	raise forms.ValidationError("CAS # is not formatted properly.  Proper formatting example: 123-01-1")
		return cd['value']
		
class ChangePasswordForm(forms.Form):
	current_pass = forms.CharField(widget=forms.PasswordInput, label="current password")
	new_pass = forms.CharField(widget=forms.PasswordInput, label="new password")
	new_pass_conf = forms.CharField(widget=forms.PasswordInput, label="confirm new password")
	
	def __init__(self, request, *args, **kwargs):
	        self.request = request
	        super(ChangePasswordForm, self).__init__(*args, **kwargs)
	
	def clean_current_pass(self):
		cd = self.cleaned_data
		d = cd['current_pass']
		if not self.request.user.check_password(d):
			raise forms.ValidationError("The current password is not correct")
		return d
			
	def clean_new_pass_conf(self):
		cd = self.cleaned_data
		if cd['new_pass'] != cd['new_pass_conf']:
			raise forms.ValidationError("New passwords do not match")
		return cd['new_pass']
		
		
class ItemActionForm(forms.Form):
	action = forms.BooleanField(required=False)
	item_id = forms.IntegerField(widget=forms.HiddenInput)
	
	def __init__(self, *args, **kwargs):
		self.item = None
		super(ItemActionForm, self).__init__(*args,**kwargs)
	
	def get_item(self):
		if 'item_id' not in self.initial:
			return 'Not Found'
		if not self.item:
		 	self.item = Item.objects.get(id=self.initial['item_id'])
		return self.item
	
ItemActionFormset = formset_factory(ItemActionForm, extra=0)

class ActionForm(forms.Form):
	action = forms.ChoiceField(
		choices=ACTION_CHOICES,
		required=True,
		widget=forms.Select(attrs={'onchange':'toggle_vis()'}))
	move_to = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
	
class ItemForm(forms.ModelForm):
	properties = forms.CharField(label='Notes',required=False)
	mol_formula = forms.CharField(label='Molecular Formula')
	cas_num = forms.CharField(label='CAS #')
	#classification = forms.CharField(widget=forms.TextInput(attrs={'onchange':'filter_class()'}))
	
	def clean_cas_num(self):
		cd = self.cleaned_data
		cas_n = cd['cas_num'].strip()
		if len(cas_n) < 5: #minimum cas len = 0-0-0
			return 
		cas = cas_n[::-1].replace('-','')[1::]
		check = cas_n[-1]

		total = 0
		for idx,val in enumerate(cas):
			total += int(val)*(idx+1)
		if (total % 10) != int(check):
			raise forms.ValidationError('Check your CAS #')
		return cas_n
	
	class Meta:
		model = Item
